var curItemId;
var type = "";
var title ="";
var bannerUrl ="";


$(document).ready(function () {
    type = getvl("type");
    if(type==0){
        $("#itemInfo").hide();
    }
    if(type==5||type==2||type==8){
        $("#bannerDiv").hide();
    }
    init(callback, 1);

    //图片
    initDropzone();
    initItemInfo(type);

});

//初始化栏目基本信息，标题banner图等
function initItemInfo(type) {
    $.ajax({
        url: urlcore + "/api/indexItem/selectItemInfoByItemNum",
        method: "get",
        dataType: "json",
        data: {num: type},
        contentType: "application/json;charset=utf-8",
        success: function (cbdata) {
            if(cbdata.data!=null){
                curItemId=cbdata.data.id;
                bannerUrl = cbdata.data.bannerUrl;
                if (null != bannerUrl) {
                    var origThumbPicHtml = "";
                    origThumbPicHtml += "<div style='float: left'> <img class='oriImage' src=\"" + bannerUrl + "\"></div>";
                    $("#origThumbPic").html(origThumbPicHtml);
                }
                console.log(cbdata);
                title = cbdata.data.title;
                if (null != title) {
                    $("#title").val(title);
                }
            }
        },
        error: function (data) {
            alert("获取详情失败");
        }


    });
}

function init(callback, current) {
    $("#thislist").html("");
    $.ajax({
        type: "get",
        url: urlcore + "/api/popGoods/selectPage?current=" + current + "&type=" + type,
        dataType: "json",
        headers: {"Content-Type": "application/json;charset=UTF-8"},
        data: {},
        success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
            if (data.success == true) {
                callback(data.data.records);
                $('#thiscount').text(data.data.total);
                $("#pager").pager({
                    pagenumber: current,
                    pagecount: data.data.pages,
                    totalcount: data.data.total,
                    buttonClickCallback: PageClick
                });
            } else if (data.code == 'OVERTIME') {
                var thisUrl = window.location.href;
                if (thisUrl.indexOf('login.html') <= -1) {
                    top.window.location.href = "login.html";
                }
            } else {
                alert(data.msg);
            }
        },
        error: function () {
            alert("获取列表失败");
        }
    });

}


//回调函数  
PageClick = function (pageclickednumber) {
    init(callback, pageclickednumber);
}

var callback = function (data) {
    var html = "", goodsName = "", goodsType = "", goodsUrl = "", markerPrice = "", returnRate = "", returnRateY = "",
        goodsStatus = "", gmtDatetime = "", id = "";
    var goodsStatusShow = "";//显示的商品状态
    var changgeStatusOptBtn = "";
    for (var i = 0; i < data.length; i++) {
        id = data[i].id;
        goodsName = data[i].goods.goodsName;
        goodsUrl = data[i].goods.goodsUrl != null ? data[i].goods.goodsUrl : "";
        mPrice = data[i].goods.mPrice;
        returnRate = data[i].goods.returnRate;
        postage = data[i].goods.postage;
        gmtDatetime=data[i].goods.gmtDatetime;
        /*邮费类型（1 江浙沪包邮 2  满九十九包邮 3  七块钱邮费  4 全国包邮（港澳台地区、西藏、新疆、内蒙古、宁夏、青海等地区除外））*/
/*        if (postage == undefined) {
            postage = "";
        } else if (postage == 1) {
            postage = "江浙沪包邮";
        } else if (postage == 2) {
            postage = "满88包邮";
        } else if (postage == 3) {
            postage = "5块钱邮费"
        } else if (postage == 4) {
            postage = "全国包邮（港澳台地区、西藏、新疆、内蒙古、宁夏、青海等地区除外）";
        }*/
        returnRateY = data[i].goods.returnRatey;
        goodsStatus = data[i].goods.goodsStatus;

        if (goodsStatus == 1) {
            goodsStatusShow = "尚未发布";
        } else if (goodsStatus == 2) {
            goodsStatusShow = "已发布上架";
        } else if (goodsStatus == 3) {
            goodsStatusShow = "已下架";
        } else {
            goodsStatusShow = "";
        }
        if (data[i].goods.goodsType == 0) {
            goodsType = "蜜哆哆";
        } else if (data[i].goods.goodsType == 1) {
            goodsType = "蜜雅阁";
        } else if (data[i].goods.goodsType == 2) {
            goodsType = "品牌馆";
        } else {
            goodsType = "";
        }
        var isHome = "";
        var isHomec = "";
        console.log(data[i]);
        if (data[i].isHome == 1) {
            isHome = "是";
            isHomec = "   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:void(0);\" onclick=\"updIsHome(" + id + "," + "0" + ")\"> 取消首页显示</a>\n";
        } else {
            isHome = "否";
            isHomec = "  \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"javascript:void(0);\" onclick=\"updIsHome(" + id + "," + "1" + ")\">设置首页显示</a>\n";
        }
        html += "  <tr id=\"" + id + "\">\n" +
            "  \t\t<td>" + (i + 1) + "</td>\n" +
            "  \t\t<td>" + goodsName + "</td>\n" +
            "  \t\t<td>" + mPrice + "</td>\n" +
            "\t\t <td class=\"footable-visible\"><img width=\"40px\" height=\"40px\" src=\"" + goodsUrl + "\"></td>\n" +
            "  \t\t<th>" + returnRate + "</th>\n" +
            "  \t\t<th>" + returnRateY + "</th>\n" +
            // "  \t\t<th>" + postage + "</th>\n" +
            "  \t\t<th>" + goodsType + "</th>\n" +
            "  \t\t<th>" + gmtDatetime + "</th>\n" +
            "  \t\t<th>" + isHome + "</th>\n" +
            "  \t\t<td>\n" +
            // "  \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_add.html?id=" + id + "\"> 修改</a>\n" +
            "   \t\t\t<a class=\"btn btn-danger btn-xs\" href=\"javascript:;\" onclick=\"doDelete(" + id + ")\"> 删除</a>\n" + isHomec +
            //"   \t\t\t<a class=\"btn btn-primary btn-xs\" href=\"goods_details.html?id=" + id + "\"> 详细</a>\n" +
            "  \t\t</td>\n" +
            "  \t</tr>";
    }
    $("#thislist").append(html);
}

//设置和取消首页显示
function updIsHome(id, type) {
    console.log(id, type);
    $.ajax({
        url: urlcore + "/api/popGoods/updIsHome?id=" + id + "&isHome=" + type,
        type: "get",
        dataType: "json",
        headers: {"Content-Type": "application/json;charset=UTF-8"},
        success: function (cbdata) {
            location.reload();
        },
        error: function (cbdata) {
            alert("更新状态失败");
        }
    })

}

//刪除
function doDelete(id) {

    $.ajax({
        type: "GET",
        url: urlcore + "/api/popGoods/deletePopGoods?id=" + id,
        dataType: "json",
        headers: {"Content-Type": "application/json;charset=UTF-8"},
        data: {},
        success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
            if (data.success == true) {
                location.reload();
            } else {
                alert(data.msg);
            }
        },
        error: function () {
            alert("删除失败");
        }
    });
}



//搜索
function searchuser() {
    var type = $('#goods_type option:selected').val();//选中的值
    init(type, callback, 1);
}

function initDropzone() {
    Dropzone.autoDiscover = false;//解决两次实例Dropzone错误，可在控制台看到该错误
// Dropzone class:
    //图修改
    goodsThumbDropzone = new Dropzone("div#editThumbPic",
        {
            url: urlcore + "/api/attachment/upload",
//          paramName: "skuUrl", // The name that will be used to transfer the file
            maxFiles: 1,
            // thumbnailWidth: 150,
            thumbnailHeight: 120,
            addRemoveLinks: true,//清除图片
            dictRemoveFile: "删除图片",//如果addRemoveLinks为 true，这段文本用来设置删除文件显示文本.
            dictCancelUpload: "取消上传",//如果addRemoveLinks为 true，这段文本用来设置取消上载链接的文本
            dictMaxFilesExceeded: "上传数量已达上限",
            previewsContainer: "#editThumbPic-pre", // 文件预览显示位置,可以为id或class选择器或html元素
            success: function (file, data) {
                //这里的$(this)其实得到的是Dropzone对象（对象数组，取第一个为当前Dropzone对象）
                console.log($(this));
                //通过查看Dropzone对象的结构得到对应div的id
                var sku_url_id = '#' + $(this)[0].element.id;
                console.log("file:", file);
                console.log("data:", data);
                bannerUrl = data.data[0];
                //重要！！为file对象添加一个url属性，将上传完成的图片url加到该属性值中，之后的removeFile和从待上传url数组中删除都依赖这个操作
                file.url = bannerUrl;
                console.log(file);
            },
            init: function () {
                this.on("addedfile", function (file) {
                    console.log("addedfile");// actions...
                });
                this.on("maxfilesexceeded", function (file) {
                    if (bannerUrl != "") {
                        goodsThumbDropzone.removeFile(file);
                        alert("已达上传数量上限");
                    }
                });
                this.on("removedfile", function (file) {
                    if (file.url != undefined && file.url == bannerUrl) {
                        bannerUrl = "";
                    }
                    //从数组中移除url,因移除的file必然先存在，所以无需判断indexOf为-1
                    console.log("removedfile", file);// actions...
                });
            }
        });
}


//保存
function save() {
    if($("#title").val()==""){
        alert("标题不能为空！");
        return;
    }
    var uptModel = {
        id: curItemId,
        title: $("#title").val(),
        bannerUrl: bannerUrl
    };

    $.ajax({
        type: "POST",
        url: urlcore + "/api/indexItem/update",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(uptModel),
        success: function (data) {
            alert("保存成功！");
            console.log("batchskudata", data);
            window.location.reload();
        },
        error: function () {

        }
    });
}




